package me.pinion.model;

import com.jfinal.kit.PathKit;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.FileRenamePolicy;
import me.pinion.model.annotation.TableBind;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@TableBind(table = "attach")
public class Attach extends XModel<Attach>{
    public static Attach dao = new Attach();

    public Attach create(String name, String type, String size, String data){
        Attach attach = new Attach();
        attach.set("name", name);
        attach.set("type", type);
        attach.set("size", size);
        attach.set("data", data);
        attach.save();
        return attach;
    }

    public File getFile(){
        return new File(PathKit.getWebRootPath() + "/" + getStr("url"));
    }


    public static Map<String, Attach> process(HttpServletRequest hsr){
        HashMap<String, Attach> fileMap = new HashMap<String, Attach>();
        Calendar calendar = Calendar.getInstance();

        final String relDir = calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/";

        File dir = new File(PathKit.getWebRootPath() + "/upload" + relDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            MultipartRequest mpr =
                    new MultipartRequest(hsr, PathKit.getWebRootPath() + "/upload", (int) 1e308, new FileRenamePolicy() {

                        public File rename(File file) {
                            File newFile = new File(PathKit.getWebRootPath() + "/upload" + relDir + System.currentTimeMillis() + file.getName().substring(file.getName().lastIndexOf('.')));
                            file.renameTo(newFile);
                            return newFile;
                        }
                    });
            Enumeration enumeration = mpr.getFileNames();
            while (enumeration.hasMoreElements()){
                String filename = enumeration.nextElement().toString();
                File file = mpr.getFile(filename);
                if (file != null){
                    String fileType = file.getName().substring(file.getName().lastIndexOf('.') + 1);
                    Attach model = new Attach();
                    model.set("rel_path", relDir + file.getName()).set("ext", fileType);
                    model.save();
                    fileMap.put(filename, model);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileMap;
    }
}
